import React, {useCallback, useEffect, useRef, useState} from "react";
import Head from "./Components/Head";
import moment from "moment";
import {getTopX} from "../../../../api/statistic";
import echarts from "echarts";

function Ranking({channelType}) {
	const cnType = channelType === 'audio' ? '广播' : '电视'
	const chartRef = useRef(null)
	const chartWrapperWidth = 500,
		chartWrapperHeight = 300
	let chartInstance = null
	const [ranking, setRanking] = useState()
	const [times, setTimes] = useState(
		() => {
			const range = []
			const start = moment().subtract(1, 'month')
			const end = moment()
			range[0] = start
			range[1] = end
			return range
		}
	)

	function renderChart() {
		console.log(1, ranking)
		const renderedInstance = echarts.getInstanceByDom(chartRef.current)
		if (renderedInstance) {
			chartInstance = renderedInstance
		} else {
			chartInstance = echarts.init(chartRef.current)
		}

		const option = {
			xAxis: {
				type: 'category',
				data: ['异常数量']
			},
			yAxis: {
				type: 'value',
				minInterval: '1'
			},
			tooltip: {
				trigger: 'axis',
				axisPointer: {
					type: 'shadow'
				}
			},
			legend: {
				data: ranking?.topx?.map(item => item.channel_name),
				type: 'plain',
				show: true,
				top: 20
			},
			color: ['#3ba1ff', '#4fcb74', '#fbd438', '#7d277d', 'rgb(240,72,100)'],
			series: ranking?.topx.map((item, index) => ({
				name: item.channel_name,
				data: [item.count],
				type: 'bar'
			}))
		}
		chartInstance.setOption(option, true)
	}

	useEffect(renderChart, [ranking])

	const onDatePickChange = useCallback((moments, values) => {
		setTimes(moments)
	}, [])

	useEffect(() => {
		getTopX({
			start: times[0].format(),
			end: times[1].format(),
			channel_type: channelType
		}).then(res => {
			setRanking(res)
		})
	}, [times])

	return (
		<>
			<h3 style={{
				borderBottom: '1px solid #aaa',
				paddingBottom: '20px',
				marginBottom: '20px',
				verticalAlign: 'middle'
			}}>{cnType}节目异常数TOP 5
			</h3>
			<Head avgCount={ranking?.avg_count} times={times} onDatePickerChange={onDatePickChange}/>
			<div ref={chartRef}
			     style={{width: `${chartWrapperWidth}px`, height: `${chartWrapperHeight}px`}}/>
		</>
	)
}

export default React.memo(Ranking)
